#!/bin/bash

# 自定义的参数 todo: 需要本地配置好hosts以及搭建好docker环境
project_name=onemap-map
port=9001

harbor_url=harbor.dockerregistry.com
harbor_project_name=gd-data
tag=2.7.0.RELEASE

image_name=${harbor_url}/${harbor_project_name}/${project_name}
image_name_and_tag=${image_name}:${tag}
echo '镜像名:tag为:'${image_name_and_tag}

# 用法说明
usage() {
	echo "执行: sh build.sh [rm_container|rm_image|build_image|save_image|push_harbor|build_jar]"
	echo "参数说明: rm_container[删除容器]|rm_image[删除镜像]|build_image[构建镜像]|save_image[保存镜像到当前目录]|push_harbor[构建并推送到harbor]|build_jar[执行maven打包]"
	exit 1
}

# 删除容器的方法
rm_container(){
  echo '...开始删除容器:'${project_name}
  containerId=`docker ps -a | grep -w ${project_name}  | awk '{print $1}'`
  if [ "$containerId" !=  "" ] ; then
      #停掉容器
      docker stop ${containerId}
      #删除容器
      docker rm ${containerId}
    echo "成功删除容器"
  fi
}

# 删除镜像方法
rm_image(){
  echo '...开始删除镜像:'${image_name}
  imageId=`docker images | grep -w ${image_name}  | awk '{print $3}'`
  if [ "$imageId" !=  "" ] ; then
      #删除镜像
      docker rmi -f ${imageId}
    echo "成功删除镜像"
  fi
}

# 打包镜像
build_image(){
  echo '...开始打包新镜像'${image_name_and_tag}
  docker build -t ${image_name_and_tag} .
}

# 保存该镜像
save_image(){
  echo '...开始保存镜像到本地:'${image_name_and_tag}
  docker save -o ${project_name}.tar ${image_name_and_tag}
}

# 推送到harbor
push_harbor(){
  echo '...开始推送镜像到harbor:'${image_name_and_tag}
  docker login -u admin -p Harbor12345 ${harbor_url}
  docker push ${image_name_and_tag}
}

# maven打包
build_jar(){
  workspace=`pwd`
  echo '...开始maven打包:'
  echo '...工作路径:'${workspace}
  cd ../../
  current_path=`pwd`
  echo '切换到根路径:'${current_path}
  mvn clean install -Dmaven.test.skip=true
  cd ${workspace}
  echo '切换回工作路径:'${workspace}
}

# 根据输入执行
case "$1" in
"build_jar")
	build_jar
;;
"rm_container")
	rm_container
;;
"rm_image")
	rm_container
  rm_image
;;
"build_image")
  build_jar
	rm_container
  rm_image
  build_image
;;
"save_image")
  build_jar
	rm_container
  rm_image
  build_image
  save_image
;;
"push_harbor")
  build_jar
	rm_container
  rm_image
  build_image
  push_harbor
;;
*)
	usage
;;
esac